#!/usr/bin/env python
'''
Copyright (C) 2008 Stephane de la Linuxerie - http://polariscorp.free.fr  -  http://linuxerie.midiblogs.com

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''
import random
import pygame
import glob
import os
import sys
import datetime
from pygame.locals import FULLSCREEN, KEYDOWN, QUIT, K_ESCAPE, K_SPACE, K_RIGHT, K_LEFT, K_UP, K_DOWN, MOUSEMOTION, K_KP_PLUS, K_KP_MINUS, KMOD_CTRL, K_s, K_e
if os.name == 'nt':
	HOME = os.getenv("USERPROFILE")
else:
	HOME = os.getenv("HOME")

REPERTOIRE_IMAGES = 'images'
CURRENT_IMAGES = ''
X = 0
POS_X = 0
SIZE_MAX = 50
TABLEAU_FOND = glob.glob(os.path.join('fonds','*.jpg')) 
OLD_POS = 0
FR = 'fr1.png', 'fr2.png', 'fr3.png', 'fr3.png'
THEME = 'etoile.png', 'coeur.png', 'cox.png'
MODE = 'grabouille'
RUN = 'attrape'
VL_RECT = pygame.Rect(0, 0, 0, 0)

def intro(theme):
	"""intro class."""
	global THEME, RUN, MODE
	RUN = 'attrape'
	MODE = 'grabouille'

	background_intro = pygame.image.load(os.path.join('images','grabouille.jpg')).convert()
	screen.blit(background_intro, (0,0))
	font_intro = pygame.font.Font(os.path.join(REPERTOIRE_IMAGES, 'SMARC___.TTF'), 150)
	text_quitter = font_intro.render("Options", True, (229, 229, 229), )
	screen.blit(text_quitter, (320, 550))
	text_quitter = font_intro.render("Grabouiller", True, (229, 229, 229), )
	screen.blit(text_quitter, (220, 240))
	text_quitter = font_intro.render("Attraper", True, (229, 229, 229), )
	screen.blit(text_quitter, (280, 400))
	if theme == 'fil':
		THEME = 'etoile.png', 'coeur.png', 'cox.png'
		coche_ok ((480, 150))
	elif theme == 'gar' :
		THEME = 'bomb.png', 'eprouvette.png', 'loup.png'
		coche_ok((180, 150))

	pygame.display.update()
	run()
	sys.exit(1)

def ecri_texte(texte, color, pos, size):
	"""ecriture des textes de choix sur la page d'accueil."""
	font_chx = pygame.font.Font(os.path.join(REPERTOIRE_IMAGES, 'Cookies.ttf'), size)
	text_fil = font_chx.render(texte, True, color, )
	screen.blit(text_fil, pos)
	pygame.display.update()
	return

def coche_ok(val):
	"""choix de l'option sur la page d'accueil."""
	b = pygame.sprite.Sprite() 
	img_ok = os.path.join('images','ok.png')
	b.image_alpha_ok = pygame.image.load(img_ok).convert_alpha()
	screen.blit(b.image_alpha_ok, val)
	pygame.display.update()
	return

def joue_intro(var):
	intro_fond = (os.path.join('sons', 'intro.ogg'))
	intro_sound = pygame.mixer.Sound(intro_fond)
	if var == 'ok':
		intro_sound.play()
	elif var == 'stop':
		pygame.mixer.stop()

def run():
	"""Launching pygame"""
	global MODE

	choix1 = pygame.Rect(220, 550, 545, 130)
	choix2 = pygame.Rect(220, 220, 545, 130)
	choix3 = pygame.Rect(220, 411, 545, 130)
	grabouilleuse = pygame.Rect(495, 150, 220, 32)
	grabouilleur = pygame.Rect(210, 150, 207, 32)
	quitter = pygame.Rect(400, 730, 350, 36)

	ecri_texte ('Grabouilleur', (255, 255, 255), (220, 150), 30)
	ecri_texte ('Grabouilleuse', (255, 255, 255), (520, 150), 30)
	ecri_texte ('Quitter', (255, 255, 255), (430, 730), 30)
	joue_intro('ok')

	while 1:
		souris_position = pygame.mouse.get_pos()
		for event in pygame.event.get():
			btn = pygame.mouse.get_pressed()
			if event.type == QUIT:
				return
			elif choix1.collidepoint(souris_position) :
				if btn[0] == True:
					option()
			elif choix3.collidepoint(souris_position) :
				if btn[0] == True:
					MODE = 'attrape'
					PaintNini().run()
			elif choix2.collidepoint(souris_position) :
				if btn[0] == True:
					PaintNini().run()
			elif grabouilleur.collidepoint(souris_position) :
				if btn[0] == True:
					intro('gar')	
			elif grabouilleuse.collidepoint(souris_position) :
				if btn[0] == True:
					intro('fil')
			elif quitter.collidepoint(souris_position) :
				if btn[0] == True:
					sys.exit(1)
					
def option():
	options_retour = pygame.Rect(280, 680, 370, 90)
	background_option = pygame.image.load(os.path.join('images','options.png')).convert()
	screen.blit(background_option, (0,0))
	pygame.display.update()
	while 1:
		souris_position = pygame.mouse.get_pos()
		for event in pygame.event.get():	
			if event.type == QUIT:
				sys.exit(1)
			elif options_retour.collidepoint(souris_position) :
				btn = pygame.mouse.get_pressed()
				if btn[0] == True:
					intro('fil')

class PaintNini:
	"""Main class."""
	def __init__(self):
		self.change_background('change')
		joue_intro('stop')

	def run(self):
		"""Launching pygame"""
		pygame.display.update()
		self.loop()
		intro('fil')

	def loop(self):
		"""loop."""
		get_out = False
		while not get_out:
			get_out = self.handleevents()
			
	def sauvegarde(self):
		"""sauvegarde l'image."""
		dte =  datetime.date.today()
		tar_img = os.path.join(HOME, 'mes_grabouilles', 'image_du-'+ str(dte) +'.bmp')
		if os.path.isdir(os.path.join(HOME, 'mes_grabouilles')) :
			pygame.image.save(screen, tar_img)
		return()

	def affiche_fr(self):
		global RUN
		RUN = 'pas_attrape'
		size = random.randrange(15, 200)
		x = random.randrange(0, 1024)-size 
		y = random.randrange(0, 768)-size 
		current = random.choice(FR)
		img_attrape = os.path.join('images', current)
		image_attrape_ok = pygame.image.load(img_attrape).convert_alpha()
		image_attrape_ok = pygame.transform.scale(image_attrape_ok, (size, size))
		screen.blit(image_attrape_ok, (x, y))
		return x,y,size

	def handleevents(self):
		"""Events notify"""
		global OLD_POS, POS_X, VL_RECT, RUN
		get_out = False
		mods = pygame.key.get_mods()

		for event in pygame.event.get():

			if event.type == QUIT:
				get_out = True
			elif event.type == KEYDOWN:

              			if (event.key == K_e and mods & KMOD_CTRL):
					intro('fil')
				elif (event.key == K_s and mods & KMOD_CTRL):
					self.sauvegarde()
				elif event.key == K_SPACE:
					self.change_background('efface')
				elif event.key == K_RIGHT:
					self.change_background('change')
				elif event.key == K_LEFT:
					self.change_background('change')	
				elif event.key == K_DOWN:
					self.change_background('change')
				elif event.key == K_UP:
					self.change_background('change')
				elif event.key == K_KP_PLUS:
					self.change_size(5)
					return()
				elif event.key == K_KP_MINUS:
					self.change_size(-5)
					return()
				else:
					valeur = pygame.key.name(event.key)
					if valeur == 'left ctrl':
						return()
					size_texte = random.randrange(200, 300)
					col1 = random.randrange(0, 255)
					col2 = random.randrange(0, 255)
					col3 = random.randrange(0, 255)
					pos = pygame.mouse.get_pos()
					font = pygame.font.Font(os.path.join(REPERTOIRE_IMAGES, 'SMARC___.TTF'), size_texte)
					text = font.render(valeur, True, (col1, col2, col3), )

					if pos[0] == OLD_POS :
						POS_X = POS_X + 100
					else :
						POS_X = pos[0]

					screen.blit(text, (POS_X-50,pos[1]-200))
					self.joue_son(os.path.join('sons', 'tape.wav'))
					OLD_POS = pos[0]
					pygame.display.update()

			elif event.type == MOUSEMOTION:
				retour_click = pygame.mouse.get_pressed()
				if MODE == 'attrape':
					if RUN == 'attrape':
						vl = self.affiche_fr()
						VL_RECT = pygame.Rect(vl[0], vl[1], vl[2], vl[2])
					if VL_RECT.collidepoint(pygame.mouse.get_pos()) :
						self.joue_son(os.path.join('sons', 'tada.ogg'))
						ecri_texte('BRAVO !', (255, 255, 255), (100, 250), 250)
						pygame.time.wait(500)
						RUN = 'attrape'
						self.change_background('change')

				if retour_click[2] == True:
					self.joue_son(os.path.join('sons', 'rien.ogg'))
					return()
				elif retour_click[0] == True:
					self.paintnini(pygame.mouse.get_pos(), 1)
				elif retour_click[1] == True:
					self.paintnini(pygame.mouse.get_pos(), 2)
				else:
					self.paintnini(pygame.mouse.get_pos(), 0)	
		return get_out
	
	def change_background(self,choix):
		"""Change background ou efface le tableau tout en gardant le fond choisi"""
		global CURRENT_IMAGES, VL_RECT, MODE, RUN
		if choix == 'change':
			RUN = 'attrape'
			image_du_fond = random.choice(TABLEAU_FOND)
			CURRENT_IMAGES = image_du_fond
			background = pygame.image.load(image_du_fond).convert()
			for x in range(10):
				background_old = pygame.image.load(CURRENT_IMAGES).convert()
				background_old.set_alpha((x * 255) / 10.0, pygame.RLEACCEL)
				screen.blit(background_old, (0,0))
				pygame.display.flip()

		elif choix == 'efface':
			RUN = 'attrape'
			background = pygame.image.load(CURRENT_IMAGES).convert()
			screen.blit(background, (0, 0))
			pygame.display.flip()

		if MODE == 'attrape':
			if RUN == 'attrape':
				vl = self.affiche_fr()
				VL_RECT = pygame.Rect(vl[0], vl[1], vl[2], vl[2])

	def change_size(self, ratio):
		"""changing pencil size"""
		global SIZE_MAX
		SIZE_MAX = SIZE_MAX + ratio

	def joue_son(self, sons):
		sound = pygame.mixer.Sound(sons)
		if pygame.mixer.get_busy():
			return()
		else:
			sound.set_volume(.5)
			sound.play()

	def paintnini(self, pos, getbtn):
		"""select color and size"""
		global SIZE_MAX
		CLIC_MILIEU = 'vide1.png', 'vide1.png', THEME[0] , 'vide1.png', 'vide1.png', 'vide1.png',  THEME[1], 'vide1.png', 'vide1.png', 'vide1.png'
		CLIC_GAUCHE = 'vide1.png',  THEME[2], 'vide1.png', 'vide1.png', 'vide1.png', 'vide1.png', 'vide1.png', 'vide1.png'
		if SIZE_MAX < 4:
			SIZE_MAX = 4
		img_background = os.path.join(REPERTOIRE_IMAGES, random.choice(CLIC_MILIEU))
		image_alpha = pygame.image.load(img_background).convert_alpha()
		img_background_cox = os.path.join(REPERTOIRE_IMAGES, random.choice(CLIC_GAUCHE))
		image_alpha_cox = pygame.image.load(img_background_cox).convert_alpha()
		col1 = random.randrange(0, 255)
		col2 = random.randrange(0, 255)
		col3 = random.randrange(0, 255)
		size = random.randrange(0, SIZE_MAX)
		size_coeur_etoile = random.randrange(0, 90) 
		nb_zoom = random.random()*2
		angle_rot = random.randrange(0, 360) 
		img_x_pos = random.randrange(-30, 30)
		img_y_pos = random.randrange(-30, 30)
		if getbtn == 1:
			#image_alpha_cox = pygame.transform.scale(image_alpha_cox, (size_coeur_etoile, size_coeur_etoile))
			image_alpha_cox = pygame.transform.rotozoom(image_alpha_cox, angle_rot, nb_zoom)
			screen.blit(image_alpha_cox, (pos[0]+img_x_pos, pos[1]+img_y_pos))
			self.joue_son(os.path.join('sons', 'oops.wav'))
		elif getbtn==2:
			image_alpha = pygame.transform.scale(image_alpha, (size_coeur_etoile, size_coeur_etoile))
			screen.blit(image_alpha, (pos[0]+img_x_pos, pos[1]+img_y_pos))
			self.joue_son(os.path.join('sons', 'rire.wav'))
		else:
			pygame.draw.circle(screen, (col1, col2, col3), pos, size, 0)
		pygame.display.update()

if __name__ == '__main__' : 
	if os.path.isdir(os.path.join(HOME, 'mes_grabouilles')) == False :
		os.mkdir(os.path.join(HOME, 'mes_grabouilles'))
	pygame.init()
	pygame.mixer.pre_init(44100, -16, 2, 1024) 
	pygame.mixer.init() 
	pygame.display.set_caption('Grabouille')
	#screen = pygame.display.set_mode((1024, 768))
	screen = pygame.display.set_mode((1024, 768), FULLSCREEN)
	intro('fil')
